//
//  Status.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/5/10.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {

    var created_at: String?{
        didSet{
//            if let time = created_at{
//                let date = NSDate.DateByStr(time)
//                created_at = date.convertTime
           }
        
    }

/// 转换好的时间显示
var sina_time: String?{
    let createdDate = NSDate.DateByStr(created_at!)
    // 2.获取格式化之后的时间字符串
    return createdDate.convertTime ?? ""
}


    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    
    var source: String?{
        didSet{
            if let sourcexx = source{// 防止source为nil
                
                if sourcexx == "" {// 防止source为""
                    return
                }
                // 开始截取的位置
                let startIndex = (sourcexx as NSString).rangeOfString(">").location + 1
                
                // 截取的长度
                let lengthIndex = (sourcexx as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startIndex
                
                source = "来自->" + (sourcexx as NSString).substringWithRange(NSMakeRange(startIndex, lengthIndex))
            }
             }
    }
    
    /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
       
        didSet{

            withMap_urls = [NSURL]()
            withMap_large_urls = [NSURL]()

            for dict in pic_urls!
            {
                if let urlStr = dict["thumbnail_pic"] as? String
                {
                    
                    let large_urlStr  = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    
                    withMap_urls?.append(NSURL(string: urlStr )!)
                    withMap_large_urls?.append(NSURL(string: large_urlStr)!)
                }
                
                }
        }
    }
        
    
    //原创微博 正文下面的插图  --缩略图
    var  withMap_urls: [NSURL]?
    
    // 原创微博正文下面的插图  --大图
    var  withMap_large_urls: [NSURL]?
    
    // 用户模型
    var user: User?
    
    // 转发微博的模型
    var retweeted_status: Status?
    
    /// 因为原创的插图和转发的插图不可能同时出现
    var chaTu_urls: [NSURL]?{
        return retweeted_status != nil ? retweeted_status?.withMap_urls : withMap_urls
    }
    
    var  chaTu_large_urls: [NSURL]? {
        return retweeted_status != nil ? retweeted_status?.withMap_large_urls : withMap_large_urls
    }
    

    // 网络请求类方法
    class func loadStatusHttpRequest(since_id: Int, max_id: Int, finished: (modelArr: [Status]?, error: NSError?)->()) {
       
        StatusCache.loadWeiBoStatusData(since_id, max_id: max_id) { (dictArr, error) in
            
            let modelArr = dictConverModel(dictArr!)
            
            // 缓存配图
            cacheStatusImages(modelArr, finished: finished)
        }
        
}
    
    
    /// 缓存配图
    class func cacheStatusImages(list: [Status], finished: (models:[Status]?, error:NSError?)->()) {
        
        if list.count == 0{
           finished(models: list, error: nil)
           return
        }
        // 1.创建一个组
        let group = dispatch_group_create()
        
        // 1.缓存图片
        for status in list
        {
            // 1.1判断当前微博是否有配图, 如果没有就直接跳过
            //            if status.storedPicURLS == nil{
            //                continue
            //            }
            // Swift2.0新语法, 如果条件为nil, 那么就会执行else后面的语句
            //            status.storedPicURLS = nil
          
            guard let _ = status.chaTu_urls else
            {
                continue
            }
            
            for url in status.chaTu_urls!
            {
                // 将当前的下载操作添加到组中
                dispatch_group_enter(group)
                
                // 缓存图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    // 离开当前组
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 2.当所有图片都下载完毕再通过闭包通知调用者
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            // 能够来到这个地方, 一定是所有图片都下载完毕
            finished(models: list, error: nil)
        }
    }
    
    
    // 将数据模型转换为字典模型
    class func dictConverModel(dictArr: [[String: AnyObject]]) ->[Status] {
        var arr =  [Status]()
        for dict in dictArr {
            
          arr.append(Status(dict: dict))
        }
        return arr
    }
    
    //构造方法，字典转模型
    init(dict: [String: AnyObject]) {
        
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
        
    
    override func setValue(value: AnyObject?, forKey key: String) {
        super.setValue(value, forKey: key)
      //  print("key: \(key)    value: \(value)")
        
        if "user" == key
        {
            user = User(dict: value as! [String: AnyObject])
            return
        }
        else if "retweeted_status" == key
        {
            retweeted_status = Status(dict: value as! [String: AnyObject])
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    // 防止KVC 键值编码的错误
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
      
    }
    
 }
